package com.dlc.shop.user.platform.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dlc.shop.bean.param.ScoreExpireParam;
import com.dlc.shop.common.annotation.SysLog;
import com.dlc.shop.common.bean.SysConfig;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.Json;
import com.dlc.shop.service.SysConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;


/**
 * 积分过期配置
 * @author lgh
 */
@Tag(name = "积分过期配置")
@RestController
@RequestMapping("/user/scoreExpire")
@AllArgsConstructor
public class ScoreExpireConfigController {

    private final SysConfigService sysConfigService;

    /**
     * 配置信息
     */
    @GetMapping("/info/{key}")
    @PreAuthorize("@pms.hasPermission('user:scoreSonfig:info')")
    @Operation(summary = "配置信息" , description = "配置信息")
    @Parameter(name = "key", description = "参数名" )
    public ServerResponseEntity<ScoreExpireParam> info(@PathVariable("key") String key){
        SysConfig config = sysConfigService.getOne(new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getParamKey,key));
        if(Objects.isNull(config)){
            return ServerResponseEntity.success();
        }
        ScoreExpireParam expireParam = Json.parseObject(config.getParamValue(), ScoreExpireParam.class);
        return ServerResponseEntity.success(expireParam);
    }

    @SysLog("保存配置")
    @PostMapping
    @Operation(summary = "保存配置" , description = "保存配置")
    @PreAuthorize("@pms.hasPermission('user:GrowthConfig:save')")
    public ServerResponseEntity<Void> save(@RequestBody @Valid ScoreExpireParam expireParam){
        SysConfig config = new SysConfig();

        String paramValue = Json.toJsonString(expireParam);
        config.setParamKey(Constant.SCORE_EXPIRE);
        config.setParamValue(paramValue);
        config.setRemark("积分过期规则");
        if (sysConfigService.count(new LambdaQueryWrapper<SysConfig>()
                .eq(SysConfig::getParamKey, config.getParamKey())) > 0) {
            sysConfigService.update(new LambdaUpdateWrapper<SysConfig>()
                    .set(SysConfig::getParamValue,config.getParamValue())
                    .set(SysConfig::getRemark,config.getRemark())
                    .eq(SysConfig::getParamKey,config.getParamKey()));
        }else {
            sysConfigService.save(config);
        }
        sysConfigService.removeSysConfig(Constant.SCORE_EXPIRE);
        return ServerResponseEntity.success();
    }

}
